package com.atguigu.gmall.order.controller;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.cart.client.CartFeignClient;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.cart.CartInfo;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.user.UserAddress;
import com.atguigu.gmall.order.Service.OrderInfoService;
import com.atguigu.gmall.product.client.ProductFeignClient;
import com.atguigu.gmall.user.client.UserFeignClient;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * @program: gmall-parent
 * @author: Mr.Zhuo
 * @create: 2022-04-15 21:20
 **/
@RestController
@RequestMapping("api/order")
public class OrderApiController {

    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private CartFeignClient cartFeignClient;

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ProductFeignClient productFeignClient;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    /**
     * 拆单业务
     *
     * @param request
     * @return
     */
    @PostMapping("orderSplit")
    public String orderSplit(HttpServletRequest request) {
        String orderId = request.getParameter("orderId");
        String wareSkuMap = request.getParameter("wareSkuMap");

        // 拆单
        List<OrderInfo> orderInfoList = this.orderInfoService.splitOrder(orderId, wareSkuMap);

        List<Map> mapList = orderInfoList.stream().map(orderInfo -> {
            Map map = orderInfoService.initWareOrder(orderInfo);
            return map;
        }).collect(Collectors.toList());

        // 进行返回数据
        return JSON.toJSONString(mapList);
    }


    /**
     * 根据订单id获取数据
     *
     * @param orderId
     * @return
     */
    @GetMapping("inner/getOrderInfo/{orderId}")
    public OrderInfo getOrderInfo(@PathVariable("orderId") Long orderId) {

        // 调用service
        return orderInfoService.getOrderInfo(orderId);
    }


    @ApiOperation("我的订单")
    @GetMapping("auth/{page}/{limit}")
    public Result<IPage<OrderInfo>> index(
            @ApiParam(name = "page", value = "当前页码", required = true)
            @PathVariable Long page,

            @ApiParam(name = "limit", value = "每页记录数", required = true)
            @PathVariable Long limit,
            HttpServletRequest request
    ) {
        Page<OrderInfo> orderInfoPage = new Page<>(page, limit);

        // 用户id
        String userId = AuthContextHolder.getUserId(request);

        // 调用service层
        IPage<OrderInfo> orderInfoIPage = orderInfoService.indexOrderInfo(orderInfoPage, userId);

        return Result.ok(orderInfoIPage);
    }


    @PostMapping("/auth/submitOrder")
    public Result submitOrder(@RequestBody OrderInfo orderInfo,
                              @RequestParam("tradeNo") String tradeNo,
                              HttpServletRequest request
    ) {
        // 获取当前用户id
        String userId = AuthContextHolder.getUserId(request);

        // 设置当前用户id值
        orderInfo.setUserId(Long.parseLong(userId));

        // 防止客户重复提交
        Boolean result = orderInfoService.compareTradeNo(tradeNo, userId);

        if (!result) {
            return Result.fail().message("请不要重复提交订单");
        }

        // 进行库存校验
        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        for (OrderDetail detail : orderDetailList) {
            List<CompletableFuture> futureList = new ArrayList<>();
            Long skuId = detail.getSkuId();
            List<String> errorList = new ArrayList<>();

            // 库存检索
            CompletableFuture<Void> stockCompletableFuture = CompletableFuture.runAsync(() -> {

                // 首先我们需要校验库存系统
                Boolean resultStock = orderInfoService.checkStock(skuId, detail.getSkuNum());
                if (!resultStock) {
                    String msg = detail.getSkuName() + "库存不够哦~~";
                    errorList.add(msg);
                }
            }, threadPoolExecutor);
            futureList.add(stockCompletableFuture);

            // 价格检索
            CompletableFuture<Void> priceCompletableFuture = CompletableFuture.runAsync(() -> {
                // 然后查询最新的价格进行提示用户信息
                BigDecimal newPrice = productFeignClient.getSkuPrice(skuId);
                BigDecimal nowPrice = detail.getOrderPrice();
                int flagPrice = newPrice.compareTo(nowPrice);
                if (flagPrice != 0) {

                    // 重新查询价格！
                    List<CartInfo> cartCheckedList = this.cartFeignClient.getCartCheckedList(userId);
                    //  写入缓存：
                    cartCheckedList.forEach(cartInfo -> {
                        this.redisTemplate.opsForHash().put(RedisConst.USER_KEY_PREFIX + userId + RedisConst.USER_CART_KEY_SUFFIX, cartInfo.getSkuId().toString(), cartInfo);
                    });
                    // 涨钱或者降价的  钱数
                    BigDecimal subtract = newPrice.subtract(nowPrice).abs();
                    // 然后给客户提供一个友善的提示
                    if (flagPrice == 1) {
                        // 涨价
                        String msg = detail.getSkuName() + "涨价" + subtract;
                        errorList.add(msg);
                    }
                    if (flagPrice == -1) {
                        // 降价
                        String msg = detail.getSkuName() + "降价" + subtract;
                        errorList.add(msg);
                    }

                }
            }, threadPoolExecutor);
            futureList.add(priceCompletableFuture);

            // 最终进行执行
            CompletableFuture.allOf(futureList.toArray(new CompletableFuture[futureList.size()])).join();

            // 然后判断是否又可以不可以进行下一步的操作
            if (!CollectionUtils.isEmpty(errorList)) {
                return Result.fail().message(StringUtils.join(errorList, ","));
            }
        }
        // 进行保存订单
        Long orderId = orderInfoService.saveOrder(orderInfo);

        // 保存完订单信息之后我们需要进行删除
        orderInfoService.delTradeNo(userId);

        // 保存完订单之后，我们还需要进行删除购物车
        // TODO

        // 返回数据
        return Result.ok(orderId);
    }


    /**
     * 确认订单
     *
     * @param request
     * @return
     */
    @GetMapping("auth/trade")
    public Result<Map<String, Object>> trade(HttpServletRequest request) {
        // 获取到用户Id
        String userId = AuthContextHolder.getUserId(request);

        //获取用户地址
        List<UserAddress> userAddressList = userFeignClient.findUserAddressListByUserId(userId);

        // 渲染送货清单
        // 先得到用户想要购买的商品！
        List<CartInfo> cartInfoList = cartFeignClient.getCartCheckedList(userId);
        // 声明一个集合来存储订单明细
        ArrayList<OrderDetail> detailArrayList = new ArrayList<>();
        for (CartInfo cartInfo : cartInfoList) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setSkuId(cartInfo.getSkuId());
            orderDetail.setSkuName(cartInfo.getSkuName());
            orderDetail.setImgUrl(cartInfo.getImgUrl());
            orderDetail.setSkuNum(cartInfo.getSkuNum());
            orderDetail.setOrderPrice(cartInfo.getSkuPrice());

            // 添加到集合
            detailArrayList.add(orderDetail);
        }
        // 计算总金额
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOrderDetailList(detailArrayList);
        orderInfo.sumTotalAmount();

        Map<String, Object> result = new HashMap<>();
        result.put("userAddressList", userAddressList);
        result.put("detailArrayList", detailArrayList);
        // 保存总金额
        result.put("totalNum", detailArrayList.size());
        result.put("totalAmount", orderInfo.getTotalAmount());

        // 每次生成订单的时候 生成一个随机的tradeNo
        String tradeNo = orderInfoService.getTradeNo(userId);
        result.put("tradeNo", tradeNo);
        return Result.ok(result);
    }
}
